﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Bootstrap;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using Dogshow.Model;
using Dogshow.Win.DataAccess;
using Ninject;

namespace Dogshow.Win.UserControls
{
    public partial class IzborKinologa : UserControl
    {
        private BindingList<Kinolog> m_Source = new BindingList<Kinolog>(); 

        public IzborKinologa()
        {
            InitializeComponent();
            lookUpEdit1.ProcessNewValue += OnProcessNewValue;
            lookUpEdit1.Properties.DataSource = m_Source;
            lookUpEdit1.EditValueChanged += (s, e) => Kinolog = lookUpEdit1.EditValue as Kinolog;
            lookUpEdit1.ButtonClick += (s, e) =>
            {
                if (e.Button.Kind == ButtonPredefines.Delete) Kinolog = null;
            };
        }

        private Kinolog m_Kinolog;
        [Bindable(true)]
        public Kinolog Kinolog
        {
            get { return m_Kinolog; }
            set
            {
                m_Kinolog = value;
                if (Kinolog != null)
                {
                    lookUpEdit1.EditValue = Kinolog;
                    if (!m_Source.Any(x => x.Id == Kinolog.Id))
                    {
                        m_Source.Clear();
                        m_Source.Add(Kinolog);
                    }
                }
                else
                {
                    lookUpEdit1.EditValue = null;
                }
            }
        }

        public Size ControlSize
        {
            get { return lookUpEdit1.Size; }
            set { lookUpEdit1.Size = value; }
        }

        private void OnProcessNewValue(object sender, ProcessNewValueEventArgs e)
        {
            var lookup = (LookUpEdit) sender;
            var text = e.DisplayValue as string;
            if (!String.IsNullOrEmpty(text))
            {
                var kinolozi = GetDataService().VratiKinologaSaImenom(text).ToList();
                m_Source = new BindingList<Kinolog>(kinolozi);
                if (kinolozi.Count > 0)
                {
                    lookup.Properties.DataSource = m_Source;
                    lookup.ShowPopup();    
                }
            }
            e.Handled = false;
        }

        private static IDataService GetDataService()
        {
            var kernel = (IKernel)Bootstrapper.Container;
            return kernel.Get<IDataService>();
        }
    }
}
